<template>
    <div class="dashboard-container">
        <div class="container">
            <!-- 按钮添加 -->
            <div class="tableBar">
                <el-input v-model="input" placeholder="请输入账号昵称" style="width: 250px;" clearable
                          @keyup.enter.native="handleQuery">
                    <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer"></i>
                </el-input>
                <div class="tableLab" style="display: inline-block;margin-left: 0px;">
                    <el-date-picker v-model="orderTime" clearable value-format="yyyy-MM-dd HH:mm:ss"
                                    type="datetimerange" unlink-panels placeholder="选择日期" range-separator="至"
                                    start-placeholder="开始日期" end-placeholder="结束日期"
                                    :default-time="['00:00:00', '23:59:59']"
                                    style="width: 400px;margin-left: 20px;"></el-date-picker>
                    <el-button type="primary" class="search-btn" @click="handleQuery">查询</el-button>
                </div>
                <el-button-group class="crud-opts-right" style="display: block;float: right;">
                    <el-button style="margin-right: 10px;" size="mini" type="success" icon="el-icon-ali-qiyong"
                               @click="statusHandle('0')">
                        批量批准
                    </el-button>
                    <el-button style="margin-right: 10px;" size="mini" type="warning" icon="el-icon-ali-jinyong"
                               @click="statusHandle('1')">
                        批量禁用
                    </el-button>
                    <el-button size="mini" type="danger" icon="el-icon-ali-shanchu" @click="deleteHandle('批量', null)">
                        批量删除
                    </el-button>
                </el-button-group>
            </div>
        </div>

        <!-- el-table展示 -->
        <el-table v-loading="loading" :data="tableData" style="width: 100%" class="tableBox" border fit stripe
                  tooltip-effect="dark" :header-cell-class-name="'headerBg'" @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="40px" style="border: none;"
                             :selectable="checkboxT"></el-table-column>
            <el-table-column align="center" label="注册时间" prop="createTime" :formatter="formatDate" min-width="10%">
            </el-table-column>
            <el-table-column align="center" label="用户名" prop="username" min-width="7%"></el-table-column>
            <el-table-column align="center" label="昵称" prop="nickname" min-width="10%"></el-table-column>
            <el-table-column align="center" label="密码" prop="password" min-width="10%"></el-table-column>
            <el-table-column align="center" label="审批状态" min-width="5%">
                <template slot-scope="scope">
                    <el-tag effect="dark" type="primary" v-if="scope.row.status == '1'">已批准</el-tag>
                    <el-tag effect="dark" type="warning" v-if="scope.row.status == '0'">待批准</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="权限" min-width="5%">
                <template slot-scope="scope">
                    <el-tag type="danger" v-if="scope.row.role == 'super'">root</el-tag>
                    <el-tag type="success" v-if="scope.row.role == 'common'">普通</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="10%">
                <template slot-scope="scope">
                    <el-button type="text" size="midium" @click="statusHandle(scope.row) "
                               :disabled="scope.row.role == 'super'">
                        {{ scope.row.status == '0' ? '批准' : '禁用' }}
                    </el-button>
                    <el-button type="text" size="midium" class="delBut common"
                               @click="deleteHandle('单删', scope.row.id)"
                               :disabled="scope.row.role == 'super'">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 底部分页 -->
        <el-pagination style="text-align: center;" class="pageList" :page-sizes="[7,9,13]" :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper" :total="counts" :current-page.sync="page"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </el-pagination>
    </div>
    </div>
</template>

<script>
    import {query, adminStatus, deleteById} from '@/api/administrator.js'
    import {
        Loading
    } from 'element-ui'
    // import axios from 'axios'
    export default {
        name: 'Activity',
        data() {
            return {
                loading: true,
                orderTime: [],
                user: {},
                checkList: [],
                tableData: [],
                input: '',
                counts: 0,
                page: 1,
                ids: '',
                pageSize: 7,
                id: '',
                status: ''
            }
        },
        created() {
            this.$store.commit('setPath', '活动管理')
            this.init()
        },
        methods: {
            async init() {
                const params = {
                    page: this.page,
                    pageSize: this.pageSize,
                    name: this.input ? this.input : "",
                    duration: this.orderTime ? this.orderTime.join('--') : ""
                }
                await query(params).then(res => {
                    this.loading = false
                    console.log(this.page)
                    this.tableData = res.data.administrators
                    this.counts = parseInt(res.data.total)
                }).catch(err => {
                    this.loading = false
                    this.$message.error('请求出错了：' + err)
                })
            }, //方法区
            formatDate(row, column) {
                // 获取单元格数据
                let data = row[column.property]
                if (data == null) {
                    return null
                }
                let dt = new Date(data)
                return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt
                    .getMinutes()
                // + dt.getSeconds()
            },
            getImage(image) {
                return `/api/common/download?name=${image}`
            },
            checkboxT(row, rowIndex) {
                return row.role != 'super'
            },
            handleSizeChange(val) {
                this.pageSize = val
                this.init()
            },

            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${file.name}？`);
            },
            handleRemove(file, fileList) {
                this.imageUrl = ''
                deleteFile(file.response.name).then(res => {
                    if (res.data.status == 'success') {
                        this.$message.success("移除成功！")
                        this.url = ""
                    } else if (res.data.status == 'error') {
                        this.$message.error("移除失败！")
                    }
                }).catch(err => {
                    this.$message.error("发生错误了！" + err)
                })
            },
            handleCurrentChange(val) {
                this.page = val
                this.init()
            },

            handleQuery() {
                this.page = 1;
                this.init();
            },

            handleRole(row) {
                changeRole(row).then(res => {
                    if (res.data == '1') {
                        this.$message.success("权限更改成功！")
                        this.handleQuery()
                    } else {
                        this.$message.error("操作失败")
                    }
                }).catch(erroe => {
                    this.$message.error("发生错误了！" + error)
                })
            },

            save() {
                this.$refs['userForm'].validate(async (valid) => {
                    console.log(this.user)
                    if (valid) { // 表单校验合法
                        if (this.user.password !== this.user.confirmPassword) {
                            this.$message.error("两次输入的密码不一致")
                            return false
                        }
                        await saveOrUpdate(this.user).then(res => {
                            if (JSON.stringify(res.data) == '0') {
                                this.$message.error("用户已存在！")
                            } else {
                                this.$message.success("操作成功")
                                this.dialogFormVisible = false
                                this.init()
                            }
                        }).catch(err => {
                            this.$message.error("出错了：" + err)
                        })
                    }

                })
            },

            // 全部操作
            handleSelectionChange(val) {
                let checkArr = []
                val.forEach((n) => {
                    checkArr.push(n.id)
                })
                console.log(val)
                this.checkList = checkArr
            },

            //状态更改
            statusHandle(row) {
                let params = {}
                if (typeof row === 'string') {
                    if (this.checkList.length === 0) {
                        this.$message.error('批量操作，请先勾选操作用户！')
                        return false
                    }
                    params.id = this.checkList.join(',')
                    params.status = row
                } else {
                    params.id = row.id
                    params.status = row.status ? '0' : '1'
                }
                this.dishState = params
                this.$confirm('确认更改该用户状态?', '提示', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                    'type': 'warning'
                }).then(() => {
                    adminStatus(this.dishState).then(res => {
                        console.log(res.data.code)
                        if (res.data.code == 1) {
                            this.$message.success('用户状态已经更改成功！')
                            this.handleQuery()
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
            },

            // 删除
            deleteHandle(type, id) {
                console.log(id)
                if (type === '批量' && id === null) {
                    if (this.checkList.length === 0) {
                        return this.$message.error('请选择删除对象')
                    }
                }
                this.$confirm('确认删除该用户, 是否继续?', '确定删除', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                }).then(() => {
                    deleteById(type === '批量' ? this.checkList.join(',') : id).then(res => {
                        if (res.data == '1') {
                            this.$message.success('删除成功！')
                            this.handleQuery()
                        } else {
                            this.$message.error('操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
            },
        }
    }
</script>

<style>
    .dashboard-container .container .tableBox {
        width: 100%;
        border: solid 2px #f3f4f7;
        border-radius: 2px;
    }

    .el-link {
        margin-left: 15px;
    }

    .delBut {
        color: #f56c6c !important;
        position: relative;
    }

    .common::after {
        content: "";
        position: absolute;
        right: -6px;
        height: 14px;
        width: 0px;
        border-right: solid 1px #d1d3d9 !important;
    }
</style>
